#include"socket.hpp"
#include<iostream>
#include<unistd.h>
#include<functional>
#include"servercal.hpp"
using namespace std;
using fun_t=function<string(string&package)>;
class tcpserver
{
public:
tcpserver(uint16_t port,fun_t callback)
:port_(port)
,callback_(callback)
{
}

bool  initserver()
{
listensock_.Socket();
listensock_.Bind(port_);
listensock_.Listen();
return true;
}


void run()
{

while(1)
{
  string clientip;
  uint16_t clientport;
  int sockfd=listensock_.Accept(&clientport,&clientip);
   if(sockfd<0)
   continue;
  
  if(fork()==0)
   { string info;
     listensock_.Close(listensock_.sockfd_);
     while(1)
     {
      char buffer[128];
      int n=read(sockfd,buffer,sizeof(buffer));
      if(n>0)
        {

          buffer[n]=0;
          
          info+=buffer;
          cout<<info<<endl;

       
           string str=callback_(info);  //计算机处理完的结果
        
           if(str.empty())continue;

           write(sockfd,str.c_str(),str.size());
         
           

        

       
        }
    else if(n==0)
        break;
    else 
        break;

     }

     exit(0);
     listensock_.Close(sockfd);




   }
   

   listensock_.Close(sockfd);
}


}

~tcpserver()
{
}


private:
uint16_t port_;
sock listensock_;
fun_t callback_;
};